package au.com.gworks.jump.app.wiki.client.demo;

import java.util.Map;

import org.javaongems.client.forms.Form;
import org.javaongems.client.forms.FormController;
import org.javaongems.client.stdctrls.DragAndDropListener;
import org.javaongems.client.stdctrls.DragAndDropMonitor;

import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

public class DragDrop {
	static public class TestWindow extends Form {
		private Label lblOne = new Label("[one]"); 
		private Label lblTwo = new Label("[two]"); 
		private Label lblThree = new Label("[three]");
		private ListBox droppings = new ListBox();
		private FlowPanel labelsContainer = new FlowPanel();
		private DockPanel outerPanel = new DockPanel();
		private Tester controller;
		
		public TestWindow(Tester ctrlr) {
			super(ctrlr);
			controller = ctrlr;
			initialiseLayout();
			initialiseWidgets();
			initialiseListeners();
		}
		
		private void initialiseLayout() {
			setCaption("dragging demo");
			add(outerPanel);
			labelsContainer.add(lblOne);
			labelsContainer.add(lblTwo);
			labelsContainer.add(lblThree);
			outerPanel.add(labelsContainer, DockPanel.WEST);
			outerPanel.add(droppings, DockPanel.CENTER);
		}
		
		private void initialiseWidgets() {
			droppings.addItem("initially empty");
			droppings.setVisibleItemCount(10);
		}
		
		private void initialiseListeners() {
			setFormActionListener(controller);
			controller.monitor.addDragSource(lblOne);
			controller.monitor.addDragSource(lblTwo);
			controller.monitor.addDragSource(lblThree);
			controller.monitor.addDropTarget(droppings);
		}
	}
	
	static public class Tester extends FormController implements DragAndDropListener {
		private TestWindow form;
		private DragAndDropMonitor monitor = new DragAndDropMonitor(this);
		
		public void setUp(Map config) {
			super.setUp(config);
			form = new TestWindow(this);
			setForm(form);
			int[] leftTopWidthHeight = (int[]) config.get("top.left.width.height.array");
			if (leftTopWidthHeight == null)
				leftTopWidthHeight = new int[] {0, 0, 350, 200};
			leftTopWidthHeight[2] = (int) (leftTopWidthHeight[2] * 0.8);
			leftTopWidthHeight[3] = 350;
			form.place(leftTopWidthHeight);
			form.show();
		}
		
		public void onFormShow() {
			super.onFormShow();
			monitor.start();
		}
		
		public void onFormHide() {
			super.onFormHide();
			monitor.stop();
		}
		
		public Object getModel() {
			return null;
		}

		public void onDragDrop(Widget target, Widget source, int x, int y, Event evt) {
			Label lbl = (Label) source;
			ListBox lb = (ListBox) target;
			lb.addItem(lbl.getText());
		}

		public boolean onDragOver(Widget target, Widget source, int x, int y, Event evt) {
			if ((source instanceof Label) && (target instanceof ListBox)) 
				return true;
			return false;
		}
	}
}
